package com.hopechart.micro.common.daemon;

import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.ClassUtils;

/**
 * 任务脚本守护线程
 *
 * @author daijiang@hopechart.com
 */
public class MicroDaemon implements Daemon {

    private Class<?> microApplication;

    private ConfigurableApplicationContext content;

    @Override
    public void init(DaemonContext context) throws Exception {
        System.err.println("Daemon init args: " + context.getArguments()[0]);
        this.microApplication = ClassUtils.resolveClassName(context.getArguments()[0],
                MicroDaemon.class.getClassLoader());
        System.err.println("Daemon init: " + microApplication);
    }

    @Override
    public void start() throws Exception {
        System.err.println("Daemon start:" + microApplication);
        this.content = SpringApplication.run(microApplication);
    }

    @Override
    public void stop() throws Exception {
        this.content.close();
    }

    @Override
    public void destroy() {

    }

}